package com.pinganfu.mock.control;

import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.pinganfu.mock.method.PerformsMethod;
import com.pinganfu.mock.server.server;
import com.pinganfu.mock.service.IMethodService;
import com.pinganfu.mock.service.ITrendsService;
import com.pinganfu.mock.test.HttpClientService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

public class trendsData {
	
	private String server ="未知异常";
	
	@Resource
	private static ITrendsService iTrendsService;
	
	@Resource
	private IMethodService iMethodService;
	
	public static String trendString(String r) {
		String data =""; 
		
		//当前时间
		if("date".equals(r)){
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			String request_time = df.format(new Date());
			data = request_time;
		}
		return data;
	}
	
	/*public static void main(String[] args) {
        String jsonStr = "{'head':{'version':'1'},'dataList':{'resCode':'ss','list':[{'name':'file1','type':'0'},{'name':'file2','type':'1'}]}}";
        JSONObject  dataJson=JSONObject.fromObject(jsonStr);
                JSONObject  dataList=dataJson.getJSONObject("dataList");
                JSONArray list=dataList.getJSONArray("list");
                JSONObject info=list.getJSONObject(1);
                String name=info.getString("name");
                String type=info.getString("type");
                 //System.out.println(name+type);
        //String name = jsonObject.getString("name");
        System.out.println(name);
    }

	*/
	/*public static void main(String[] args) {  
        // TODO Auto-generated method stub  
        String s="{\"businessParameters\":{\"date\":\"\",\"fee_type\":\"\",\"fund_trade_no\":\"009201510230000000297\",\"partner\":\"270\",\"retcode\":\"0000\",\"retmsg\":\"\",\"sign_key_index\":\"1\",\"sp_user\":\"00999000008334820\",\"time_end\":\"20151023140906\",\"total_fee\":\"9853.05\",\"total_fund_units\":\"9903.05\",\"transaction_id\":\"00500010201510230033330000463593\"},\"protocolParameters\":{\"channel_id\":\"PAF\",\"input_charset\":\"GBK\",\"service_version\":\"1.0\",\"sign\":\"47FF4944F159F95DB9F47FF5B4412F89B658A1C9\",\"sign_type\":\"SHA-1\"}}";  
        String[] d = {"date","34"};
        Map map=new HashMap();  
        JsonConfig jc=new JsonConfig();  
        jc.setClassMap(map);  
        jc.setRootClass(Map.class);  
        jc.setArrayMode(JsonConfig.MODE_LIST);  
        JSONObject jobj=JSONObject.fromObject(s,jc);  
        //递归遍历  
        String heheString =decodeJSONObject(d,jobj);
        
        System.out.println(heheString);
        
    }  
	
	public String data(String[] d,String js){
		Map map=new HashMap();  
        JsonConfig jc=new JsonConfig();  
        jc.setClassMap(map);  
        jc.setRootClass(Map.class);  
        jc.setArrayMode(JsonConfig.MODE_LIST);  
        JSONObject jobj=JSONObject.fromObject(js,jc); 
        
        String heheString =decodeJSONObject(d,jobj);
		return heheString;
        
	}*/
	/*public static String decodeJSONObject(String[] arr,JSONObject json){ 
		Iterator<String> keys=json.keys(); 
		JSONObject jo=null;
		JSONArray ja = null;
		Object o; 
		String key; 
		while(keys.hasNext()){ 
			key=keys.next(); 
			o=json.get(key); 
			if(o instanceof JSONObject){ 
				jo=(JSONObject)o; 
				if(jo.keySet().size()>0){ 
					decodeJSONObject(arr,jo);
				}else{ 
					System.out.println("key "+key); 
				} 
			}else if(o instanceof JSONArray){
				ja = (JSONArray)o;
				for(int i=0;i<ja.size();i++){
					decodeJSONObject(arr,ja.getJSONObject(i));
				}
			}else{
				for (int i = 0; i < arr.length; i++) {
					String cString = arr[i];
					if(cString.equals(key))
					{
						String data = iTrendsService.getTrendsValue(cString);
						String tString = trendString(data);
						System.out.println(tString);
					}
				}
				//System.out.println("value"+"--"+key+"--"+o);
			}
		} 
		String hehe = String.valueOf(json);
		return hehe;
	}*/
	
	
	public String json(String  a,String data) {
		 String json ="";
				try {
					//对json数据进行解析
					Map map=new HashMap();  
			        JsonConfig jc=new JsonConfig();  
			        jc.setClassMap(map);  
			        jc.setRootClass(Map.class);  
			        jc.setArrayMode(JsonConfig.MODE_LIST);  
			        JSONObject jobj=JSONObject.fromObject(data,jc); 
			        
				     json =decodeJSONObject(a,jobj);
				} catch (Exception e) {
					// TODO: handle exception
					System.out.println("===============异常报错=================");
				}
		 return json;
	}
	
	//对json数据进行解析修改
		public String decodeJSONObject(String method,JSONObject json){ 
			PerformsMethod performs =new PerformsMethod();
			Iterator<String> keys=json.keys(); 
			JSONObject jo=null;
			JSONArray ja = null;
			Object o; 
			String key; 
			while(keys.hasNext()){ 
				String ku="";
				key=keys.next(); 
				o=json.get(key); 
				if(o instanceof JSONObject){ 
					jo=(JSONObject)o; 
					if(jo.keySet().size()>0){ 
						decodeJSONObject(method,jo);
					}else{ 
						System.out.println("key "+key); 
					} 
				}else if(o instanceof JSONArray){
					ja = (JSONArray)o;
					for(int i=0;i<ja.size();i++){
						decodeJSONObject(method,ja.getJSONObject(i));
					}
				}else{
						Object mn = o;
						String m = (String) o;
						if(m.indexOf("${")>=0){
							String s = m.substring(m.indexOf("${")+2,m.indexOf("}"));
							m = m.substring(0,m.indexOf("${"))+data(s)+m.substring(m.indexOf("}")+1);
							
							//m =m.substring(0,m.indexOf("${"))+json2(s,method)+m.substring(m.indexOf("}")+1);
							/*if(encrypt.equals("1")){
								m = rsaSSL(m);
							}else if(encrypt.equals("3")){
								m = md5SSL(m);
							}*/
							mn = m;
						}else if (m.indexOf("@{")>=0) {
							String m2 = m.substring(m.indexOf("@{")+2,m.indexOf("}"));
							json2(m2,method);
							System.out.println("server==========="+server);
							if (server.equals("未知异常")) {
								mn = "";
							}else {
								mn =server;
							}
							server="未知异常";
							
						}else if (m.indexOf("%{")>=0){
							String m2 = m.substring(m.indexOf("%{")+2,m.indexOf("}"));
							mn =performs.method(m2);
						}
						System.out.println("第二个"+mn);
						//System.out.println(n);
						json.put(key, mn);
					}
					//System.out.println("value"+"--"+key+"--"+o);
			} 
			String hehe = String.valueOf(json);
			return hehe;
		}
		
		
		public String json_encrypt(String encrypt,String  a,String data) throws Exception {
			
			//拿到动态方法集合
					//String[] arr = a;
					
					//对json数据进行解析
					Map map=new HashMap();  
			        JsonConfig jc=new JsonConfig();  
			        jc.setClassMap(map);  
			        jc.setRootClass(Map.class);  
			        jc.setArrayMode(JsonConfig.MODE_LIST);  
			        JSONObject jobj=JSONObject.fromObject(data,jc); 
			        
					//trendsData trend = new trendsData();
				        //递归遍历  
				    //String heheString =trend.data(arr,data);
				       String json =decodeJSONObject_encrypt(encrypt,a,jobj);
				       return json;
		}
		
		//对json数据进行解析修改
			public String decodeJSONObject_encrypt(String encrypt,String method,JSONObject json) throws Exception{ 
				Iterator<String> keys=json.keys(); 
				JSONObject jo=null;
				JSONArray ja = null;
				Object o; 
				String key; 
				while(keys.hasNext()){ 
					key=keys.next(); 
					o=json.get(key); 
					if(o instanceof JSONObject){ 
						jo=(JSONObject)o; 
						if(jo.keySet().size()>0){ 
							decodeJSONObject_encrypt(encrypt,method,jo);
						}else{ 
							System.out.println("key "+key); 
						} 
					}else if(o instanceof JSONArray){
						ja = (JSONArray)o;
						for(int i=0;i<ja.size();i++){
							decodeJSONObject_encrypt(encrypt,method,ja.getJSONObject(i));
						}
					}else{
							String m = (String) o;
							String n = json2(key,method);
							System.out.println(n);
							if(m.indexOf("${")>=0){
								String s = m.substring(m.indexOf("${")+2,m.indexOf("}"));
								m = m.substring(0,m.indexOf("${"))+data(s)+m.substring(m.indexOf("}")+1);
								//m =m.substring(0,m.indexOf("${"))+json2(s,method)+m.substring(m.indexOf("}")+1);
							}else if (!n.equals("")) {
									m = n;
							}
							
							if(encrypt.equals("1")){
									m = rsaSSL(m);
							}else if(encrypt.equals("3")){
									m = md5SSL(m);
							}
							
							
							System.out.println("mmmmmmmmmmmmm=========="+m);
							System.out.println("nnnnnnnnnnnnn=========="+o);
							json.put(key, m);
						}
						//System.out.println("value"+"--"+key+"--"+o);
				} 
				String hehe = String.valueOf(json);
				return hehe;
			}
			
		
		
		public String json2(String method,String data) {
			String json ="";
			try {
				//对json数据进行解析
				Map map=new HashMap();  
		        JsonConfig jc=new JsonConfig();  
		        jc.setClassMap(map);  
		        jc.setRootClass(Map.class);  
		        jc.setArrayMode(JsonConfig.MODE_LIST);  
		        JSONObject jobj=JSONObject.fromObject(data,jc); 
		        
			        //递归遍历  
			       json =as(method,jobj);
			       System.out.println("解析后的值"+json);
			      
			} catch (Exception e) {
				// TODO: handle exception
				System.out.println("===============异常报错=================");
			}
			
			 return json;
		}
		
		
		
		//对json数据进行解析修改
				public String as(String method,JSONObject json){ 
					String ziduan ="";
					Iterator<String> keys=json.keys(); 
					JSONObject jo=null;
					JSONArray ja = null;
					Object o; 
					String key; 
					
					while(keys.hasNext()){ 
						String ziduan2="";
						key=keys.next(); 
						o=json.get(key); 
						if(o instanceof JSONObject){ 
							jo=(JSONObject)o; 
							if(jo.keySet().size()>0){ 
								as(method,jo);
							}else{ 
								System.out.println("key "+key); 
							} 
						}else if(o instanceof JSONArray){
							ja = (JSONArray)o;
							for(int i=0;i<ja.size();i++){
								as(method,ja.getJSONObject(i));
							}
						}else if(key.equals(method)){
							/*if (key.equals(method)) {
								ziduan = (String) o;
								System.out.println("value"+"--"+key+"--"+ziduan);
							}
							json.put(key, o);*/
							server = (String) o;
							System.out.println("value"+"--"+key+"--"+server);
							
						}
					} 
					//String hehe = String.valueOf(ziduan);
					return ziduan;
				}
		
		  
		public static Object exec(String cmd) {  
	        try {  
	            String[] cmdA = { "/bin/sh", "-c", cmd };  
	            Process process = Runtime.getRuntime().exec(cmdA);  
	            LineNumberReader br = new LineNumberReader(new InputStreamReader(  
	                    process.getInputStream()));  
	            StringBuffer sb = new StringBuffer();  
	            String line;  
	         while ((line = br.readLine()) != null) {  
	                sb.append(line).append(",");  
	            }  
	            return sb.toString();  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	        return null;  
	    } 
		
		
		public String ls() {
			
			String jarList = exec("ls /wls/wls81/jar").toString();  
			
			return jarList;
		}
		
		public String describe(String jarName) {
			
			String pString = exec("java -cp /wls/wls81/jar/"+jarName+"/"+jarName+".jar com.pinganfu.method.describe").toString();
			System.out.println(pString);
			return pString;
		}
		
		public String unzip(String fileName) {
			
			String pString = exec("unzip -o /wls/wls81/apache-tomcat-6.0.39/webapps/jarzip/"+fileName+" -d /wls/wls81/jar/").toString();
			
			return pString;
		}
		
		public String selectJar(String menthod) {
			
			String pString = exec("find /wls/wls81/jar/ -exec grep -l '"+menthod+".class' {} \\;").toString();
			System.out.println("pString"+pString);
			if(!pString.equals("")){

				String tmp = pString.substring(0,pString.indexOf(","));
				//String tmp = pString.replaceAll("/((.*)?)/((.*)?)/((.*)?)/((.*)?)/((.*)?)", "$9");
				
				System.out.println(tmp);
				pString= tmp;
			}else{
				pString = "没有找到"+menthod+"动态方法";
			}
			return pString;
		}

		
		public String data(String menthod){
			String parameter ="";
			trendsData data = new trendsData();
			String jarName = data.selectJar(menthod);
			System.out.println(jarName);
			if(!jarName.equals("没有找到"+menthod+"动态方法")){
				//String jarfile =jarName.substring(0, jarName.indexOf("."));
				String command ="java -cp "+jarName+" com.pinganfu.method."+menthod+""; 
				String pString = exec(command).toString();
				parameter = pString.substring(0,pString.indexOf(","));
			}else {
				parameter = "没有找到"+menthod+"动态方法";
			}
			
			return parameter;
		}
		
		
		//rsa加密
		public String rsaSSL(String data) throws Exception {
			String sr=HttpClientService.post("http://10.59.32.13:32800/caps/aesenc.do", data);
			return sr;
		}
		
		//rsa解密
		public String decrypt(String data) throws Exception {
			String sr=HttpClientService.post("http://10.59.32.13:32800/caps/aesenc.do", data);
			return sr;
		}
		
		
		//md5散列加密
		public String md5SSL(String data) throws Exception {
			String sr=HttpClientService.post("http://10.59.32.13:32800/caps/mdsign.do", data);
			return sr;
		}
		
		
		
		public static void main(String[] args) {
			trendsData t = new trendsData();
			
			/*String json ="{\"test\"}";
			//String method="1234";
			//System.out.println(t.json2(method,json));
			
			String s = json.substring(json.indexOf("}")+1);
			System.out.println(s);*/
			
			String json1 ="{\"test\":\"date\"}"; 
			String json2 ="{\"test\":\"test\"}"; 
			String menthod="123";
			System.out.println("find /wls/wls81/jar/ -exec grep -l '"+menthod+".class' {} \\;");
			
			String pString = "/wls/wls81/jar/ja.jar";
			Integer sInteger = pString.indexOf("jar/");
			String tmp = pString.substring(sInteger+4);
			System.out.println(tmp);
			//System.out.println(t.json(json1, json2));
			
		}
	    
	    
		/*public static void main(String[] args) {
			trendsData json = new trendsData();
			String data = "{\"test\":\"${date}\"}";
			String[] Date = ["date"];
			json.json( Date,data);
		}*/
}
